package com.paas.demo.shiro;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.MapCache;
import org.apache.shiro.util.SoftHashMap;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName : ShiroCredentialsMatcher 
 * @Description : 登录次数限制
 * @author : pengjie
 * @email  : 627799251@qq.com
 * @version  
 * @Date : 2019/1/21 10:19
*/
public class ShiroCredentialsMatcher extends HashedCredentialsMatcher {

    private Cache<String, AtomicInteger> passwordRetryCache = new MapCache(ShiroCredentialsMatcher.class.getSimpleName(), new SoftHashMap());

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {

        boolean match = super.doCredentialsMatch(token, info);


        String username = (String) token.getPrincipal();
        System.out.println("username = " + username + ", match = " + match);

        if (!match){
            AtomicInteger retryCount = passwordRetryCache.get(username);
            if (retryCount == null){
                retryCount = new AtomicInteger(0);
                passwordRetryCache.put(username, retryCount);
            }
            if (retryCount.incrementAndGet() > 5){
                throw new LockedAccountException();
            }
        }else {
            passwordRetryCache.remove(username);
        }

        return match;
    }
}
